package wsepForum.ui.jaxcent.states;

import jaxcent.HtmlInputButton;
import jaxcent.HtmlInputText;
import jaxcent.HtmlTextArea;
import jaxcent.JaxcentPage;
import jaxcent.Jaxception;
import wsepForum.common.elements.Message;
import wsepForum.common.elements.Section;
import wsepForum.common.elements.Topic;
import wsepForum.ui.jaxcent.IXContext;

/**
 * @author Oren
 *
 */
public class XEditor implements IXState {
	/*****************************
	 * MEMBERS                   *
	 *****************************/
	public static enum ActionType { CREATE_NEW_TOPIC, NEW_MSG_ON_TOPIC, REPLY_MSG, EDIT_MESSAGE};
	private IXContext context;
	private HtmlTextArea xContent;
	private HtmlInputText xHeader;
	private HtmlInputButton xSend;

	/*****************************
	 * CONSTRUCTOR               *
	 *****************************/
	public XEditor(IXContext context, ActionType actionType, Object[] parameters) {
		this.context = context;
		switch(actionType) {
		case CREATE_NEW_TOPIC:
			doCreateNewTopic((Section)parameters[0]);
			break;
		case NEW_MSG_ON_TOPIC:
			doNewMessage((Topic)parameters[0],null);
			break;
		case REPLY_MSG:
			doNewMessage((Topic)parameters[0],(Message)parameters[1]);
			break;
		case EDIT_MESSAGE:
			doEditMessage((Topic)parameters[0],(Message)parameters[1]);
			break;
		}
		try {
			this.xHeader.focus();
		} catch (Jaxception e) {
			jaxcentError(e);
		}
	}


	/*****************************
	 * METHODS                   *
	 *****************************/
	private void doCreateNewTopic(final Section section) {
		construct(section.getHeadLine(), "Post a message");
		try {
			xSend = new HtmlInputButton(this.context.getPage(),"xsend") {
				public void onClick() {
					try {
						String header = xHeader.getValue();
						String messagebody = xContent.getValue();
						if (validatePost(header, messagebody)) {
							xSend.setValue("Posting...");
							xSend.setDisabled(true);
							xSend.blur();
							Topic topic = context.getSession().getHandler().createTopic(section.getElementID(), header , messagebody);
							context.loadTopic(topic.getElementID(),-1);
						}
					} catch (Jaxception e) {
						jaxcentError(e);
					} catch (Exception e) {
						context.getPage().showMessageDialog("Cannot create topic! "+e);
						context.loadSection(0);
					}
				}
			};
			this.xSend.setValue("Post topic");
		} catch (Jaxception e) {
			jaxcentError(e);
		}
	}

	private void doNewMessage(final Topic topic, final Message message) {
		if (message == null) construct(topic.getHeadLine(), "Post a message");
		else {
			construct(topic.getHeadLine(), "Reply to message");
			try {
				String user = message.getUserName();
				if (user==null)
					user = "guest";
				this.xHeader.setValue("RE:"+message.getHeadLine());
				this.xContent.setInnerText(user+ " said:\n" + message.getBody() + "\n-------------\n");
			} catch (Jaxception e) {
				jaxcentError(e);
			}
		}
		try {
			xSend = new HtmlInputButton(this.context.getPage(),"xsend") {
				public void onClick() {
					try {
						String header = xHeader.getValue();
						String messagebody = xContent.getValue();
						if (validatePost(header, messagebody)) {
							xSend.setValue("Posting...");
							xSend.setDisabled(true);
							xSend.blur();
							Topic changedtopic = context.getSession().getHandler().addMessageToTopic(topic.getElementID(), header , messagebody);
							context.loadTopic(changedtopic.getElementID(),-1);
						}
					} catch (Jaxception e) {
						jaxcentError(e);
					} catch (Exception e) {
						context.getPage().showMessageDialog("Cannot create message! "+e);
						context.loadSection(0);
					}
				}
			};
			if (message == null) this.xSend.setValue("Post message");
			else this.xSend.setValue("Post reply");
		} catch (Jaxception e) {
			jaxcentError(e);
		}
	}

	private void doEditMessage(final Topic topic, final Message message) {
		construct(topic.getHeadLine(), "Edit a message");
		try {
			this.xHeader.setValue(message.getHeadLine());
			this.xContent.setInnerText(message.getBody());
		} catch (Jaxception e) {
			jaxcentError(e);
		}
		try {
			xSend = new HtmlInputButton(this.context.getPage(),"xsend") {
				public void onClick() {
					try {
						String header = xHeader.getValue();
						String messagebody = xContent.getValue();
						if (validatePost(header, messagebody)) {
							xSend.setValue("Saving...");
							xSend.setDisabled(true);
							xSend.blur();
							Topic changedtopic = context.getSession().getHandler().editMessage(topic.getElementID(), message.getElementID(), header, messagebody);
							context.loadTopic(changedtopic.getElementID(),message.getElementID());
						}
					} catch (Jaxception e) {
						jaxcentError(e);
					} catch (Exception e) {
						context.getPage().showMessageDialog("Cannot edit message! "+e);
						context.loadSection(0);
					}
				}
			};
			this.xSend.setValue("Save message");
		} catch (Jaxception e) {
			jaxcentError(e);
		}
	}

	private boolean validatePost(String header, String messagebody) {
		if ((header.length()==0) | (messagebody.length()==0)) {
			this.context.getPage().showMessageDialog("Must have header and message body!");
			return false;
		}
		return true;
	}


	/* (non-Javadoc)
	 * @see wsepForum.network.server.jax.pages.states.XState#getType()
	 */
	@Override
	public StateType getType() {
		return StateType.EDITOR;
	}


	private void construct(String title, String action) {
		this.context.setBody(
		"<h2><a id=\"xtitle\">"+title+"</a></h2>"+
		"<form><div class=\"panel\" id=\"postingbox\">"+
		"<div class=\"inner\"><span class=\"corners-top\"><span></span></span>"+
		"<h3 id=\"xaction\">"+action+"</h3>"+
		"<fieldset class=\"fields1\"><dl style=\"clear: left;\">"+
		"<dt><label for=\"subject\">Subject:</label></dt>"+
		"<dd><input type=\"text\" name=\"xsubject\" id=\"xsubject\" size=\"45\" maxlength=\"64\" tabindex=\"2\" value=\"\" class=\"inputbox autowidth\" /></dd>"+
		"</dl>	<div id=\"message-box\"><textarea name=\"xmessage\" id=\"xmessage\" rows=\"15\" cols=\"78\" tabindex=\"3\" class=\"inputbox\"></textarea>"+
		"</div></fieldset><span class=\"corners-bottom\"><span></span></span></div>"+
		"</div><div class=\"panel bg2\">"+
		"<div class=\"inner\"><span class=\"corners-top\"><span></span></span>"+
		"<fieldset class=\"submit-buttons\">"+
		"<input type=\"button\" tabindex=\"6\" id= \"xsend\" name=\"xsend\" value=\"\" class=\"button1\" />"+
		"</fieldset><span class=\"corners-bottom\"><span></span></span></div></div><hr /></form>"
		);
		JaxcentPage page = context.getPage();
		xContent = new HtmlTextArea(page,"xmessage");
		xHeader = new HtmlInputText(page,"xsubject");
	}

	private void jaxcentError(Jaxception e) {
		this.context.getPage().showMessageDialog("Problem with communicating with page fields, please try again.\n"+e.getMessage());
		this.context.loadSection(0);
	}


}
